package net.cctms.zhishu.webAppFramework.net.universalimageloader;

import android.content.Context;

import com.nostra13.universalimageloader.core.assist.ContentLengthInputStream;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import net.cctms.zhishu.webAppFramework.net.glide.OkHttpUrlLoader;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * OKhttpImageloader以及response处理功能
 *
 * Created by ccwx
 */

public class OkHttpImageLoader extends BaseImageDownloader {

    private static volatile OkHttpClient internalClient;

    public OkHttpImageLoader(Context context) {
        super(context);
    }

    protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
        Request.Builder requestBuilder = new Request.Builder().url(imageUri);
        Request request = requestBuilder.build();
        Response response;

        Call call = createConnection().newCall(request);
        response = call.execute();
        if (!response.isSuccessful()) {
            throw new IOException("Request failed with code: " + response.code());
        }
        long contentLength = response.body().contentLength();
        return new ContentLengthInputStream(new BufferedInputStream(response.body().byteStream(), BUFFER_SIZE), (int)contentLength);
    }

    protected OkHttpClient createConnection() {
        if (internalClient == null) {
            synchronized (OkHttpUrlLoader.Factory.class) {
                if (internalClient == null) {
                    internalClient = new OkHttpClient();
                }
            }
        }
        return internalClient;
    }

}
